import { invoke } from "@tauri-apps/api/core"
import { listen, UnlistenFn } from "@tauri-apps/api/event";
import { dispatch } from "./dispatcher";
import { toHex2 } from "../utils/utils";

const READ_EVENT = "read/event";

let unlisten: UnlistenFn | null = null;

async function init() {
    if (unlisten != null) {
        unlisten();
    }
    unlisten =  await listen<number[]>(READ_EVENT, (payload) => {
        dispatch(payload.payload);
    });
}

init();

export default {

    async is_open() {
        return await invoke('is_open') as boolean;
    },

    async available_ports() {
        return await invoke('available_ports') as string[];
    },

    async open(name: string, baudRate: number) {
        await invoke('open', {
            name,
            baudRate
        });
    },

    async close() {
        if (unlisten != null) {
            unlisten();
        }
        unlisten = null;
        await invoke('close');
    },

    async write(buf: number[]) {
      //  console.log('write', toHex2(Uint8Array.from(buf)));
        await invoke('write', {
            buf
        });
    }
}
